package com.todo.strategy.online.application.frontend.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.todo.common.common.entity.response.BizResponse;
import com.todo.common.common.enums.BizErrorCodeEnum;
import com.todo.common.common.enums.EnableTypeEnum;
import com.todo.common.common.exception.BizException;
import com.todo.strategy.online.application.convert.StrategyConvert;
import com.todo.strategy.online.application.entity.bo.MemoTemplateBO;
import com.todo.strategy.online.application.frontend.service.MemoTemplateAggService;
import com.todo.strategy.online.application.service.MemoTemplateService;
import com.todo.strategy.online.iface.request.*;
import com.todo.strategy.online.iface.response.MemoTemplateDetailVO;
import com.todo.strategy.online.iface.response.MemoTemplateVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author azhebuxing
 * @date 2024/11/29 19:10
 * @description
 */
@Slf4j
@Service("memoTemplateAggService")
public class MemoTemplateAggServiceImpl implements MemoTemplateAggService {

    @Resource
    private MemoTemplateService memoTemplateService;


    @Override
    public BizResponse<MemoTemplateDetailVO> queryMemoTemplateById(QueryMemoTemplateByIdParam param) {
        Long templateId = param.getTemplateId();
        MemoTemplateBO memoTemplateBO = memoTemplateService.queryMemoTemplateById(templateId);
        return BizResponse.success(StrategyConvert.convertToMemoTemplateDetailVO(memoTemplateBO));
    }

    @Override
    public BizResponse<List<MemoTemplateVO>> queryMemoTemplateListByUserId(QueryMemoTemplateListByUserIdParam param) {
        Long userId = param.get_user().getUserId();
        List<MemoTemplateBO> memoTemplateBOList = memoTemplateService.queryMemoTemplateByUserId(userId);
        return BizResponse.success(StrategyConvert.convertToMemoTemplateVOList(memoTemplateBOList));
    }

    @Override
    public BizResponse<List<MemoTemplateVO>> queryRecommMemoTemplateList() {
        //todo 当前推荐的ids 后续会配置在apollo中，目前默认对象
        List<Long> templateIdList = Lists.newArrayList(1L, 2L, 3L);
        if (CollectionUtils.isEmpty(templateIdList)) {
            return BizResponse.success(new ArrayList<>());
        }
        //当推荐数据超过20个时，随机推荐其中20个
        List<Long> recommendList = new ArrayList<>();
        if (templateIdList.size() > 20) {
            Collections.shuffle(templateIdList);
            recommendList = templateIdList.subList(0, 20);
        }
        List<MemoTemplateBO> memoTemplateBOList = memoTemplateService.queryMemoTemplateByIdList(recommendList);
        Map<Long, MemoTemplateBO> memoTemplateBOMap = memoTemplateBOList
                .stream()
                .collect(Collectors.toMap(MemoTemplateBO::getId, item -> item, (v1, v2) -> v1));

        List<Long> missIdList = new ArrayList<>();
        for (Long id : recommendList) {
            if (!memoTemplateBOMap.containsKey(id)) {
                missIdList.add(id);
            }
        }
        log.info("MemoTemplateAggService#queryRecommMemoTemplateList 查询推荐列表完成，当前推荐数据缺失部分 data:{}", JSONObject.toJSONString(missIdList));
        ArrayList<MemoTemplateBO> memoTemplateBOArrayList = new ArrayList<>(memoTemplateBOMap.values());
        return BizResponse.success(StrategyConvert.convertToMemoTemplateVOList(memoTemplateBOArrayList));
    }

    @Override
    public BizResponse<Boolean> insertMemoTemplate(InsertMemoTemplateParam param) {
        MemoTemplateBO memoTemplateBO = StrategyConvert.convertToMemoTemplateBO(param);
        Boolean inserted = memoTemplateService.insertMemoTemplate(memoTemplateBO);
        log.info("MemoTemplateAggService#insertMemoTemplate 新增模板信息完成 新增人Id：{}，结果:{}", param.get_user().getUserId(), inserted);
        return BizResponse.success(inserted);
    }

    @Override
    public BizResponse<Boolean> updateMemoTemplate(UpdateMemoTemplateParam param) {
        MemoTemplateBO memoTemplateBO = memoTemplateService.queryMemoTemplateById(param.getTemplateId());
        if (memoTemplateBO == null) {
            log.error("MemoTemplateAggService#updateMemoTemplate 当前数据不存在，无法操作，param:{}", JSONObject.toJSONString(param));
            throw new BizException(BizErrorCodeEnum.OPERATION_FAILED, "当前数据您无法操作，请刷新后重试");
        }
        if (!memoTemplateBO.getUserId().equals(param.get_user().getUserId())) {
            log.error("MemoTemplateAggService#updateMemoTemplate 当前数据不属于操作人，无法操作，param:{}，更新人Id：{}，", JSONObject.toJSONString(param), param.get_user().getUserId());
            throw new BizException(BizErrorCodeEnum.OPERATION_FAILED, "当前数据您无法操作，请刷新后重试");
        }
        MemoTemplateBO insertMemoTemplateBO = StrategyConvert.convertToMemoTemplateBO(param);
        Boolean updated = memoTemplateService.updateMemoTemplate(insertMemoTemplateBO);
        log.info("MemoTemplateAggService#updateMemoTemplate 更新模板信息完成 更新人Id：{}，更新Id：{}，结果:{}", param.get_user().getUserId(), insertMemoTemplateBO.getId(), updated);
        return BizResponse.success(updated);
    }

    @Override
    public BizResponse<Boolean> removeMemoTemplateById(RemoveMemoTemplateByIdParam param) {
        Long templateId = param.getTemplateId();
        MemoTemplateBO memoTemplateBO = memoTemplateService.queryMemoTemplateById(templateId);
        if (memoTemplateBO == null) {
            log.info("MemoTemplateAggService#removeMemoTemplateById 删除模板信息完成，数据为空 默认删除成功 删除人Id：{}，删除Id：{}", param.get_user().getUserId(), templateId);
            return BizResponse.success(true);
        }
        if (memoTemplateBO.getIsPlatform()) {
            log.warn("MemoTemplateAggService#removeMemoTemplateById 删除模板信息失败，当前模板为平台模板 param:{}，操作人Id:{}", JSONObject.toJSONString(param), param.get_user().getUserId());
            throw new BizException(BizErrorCodeEnum.ILLEGAL_OPERATION, "当前模板为平台模板，你无法删除");
        }
        if (!memoTemplateBO.getUserId().equals(param.get_user().getUserId())) {
            log.warn("MemoTemplateAggService#removeMemoTemplateById 删除模板信息失败，当前模板不属于当前用户 param:{}，操作人Id:{}", JSONObject.toJSONString(param), param.get_user().getUserId());
            throw new BizException(BizErrorCodeEnum.ILLEGAL_OPERATION, "当前模板不属于当前用户");
        }
        Boolean removed = memoTemplateService.removeMemoTemplateById(templateId);
        log.info("MemoTemplateAggService#removeMemoTemplateById 删除模板信息完成 删除人Id：{}，删除Id：{}，结果:{}", param.get_user().getUserId(), templateId, removed);
        return BizResponse.success(removed);
    }

    @Override
    public BizResponse<Boolean> copyMemoTemplateById(CopyMemoTemplateByIdParam param) {
        MemoTemplateBO memoTemplateBO = memoTemplateService.queryMemoTemplateById(param.getTemplateId());
        if (memoTemplateBO == null) {
            log.error("MemoTemplateAggService#copyMemoTemplateById 根据模板id拷贝模板失败，当前需要复制的元数据不存在 param:{}，操作人Id:{}", JSONObject.toJSONString(param), param.get_user().getUserId());
            throw new BizException(BizErrorCodeEnum.OPERATION_FAILED, "当前需要复制的元数据不存在");
        }
        if (EnableTypeEnum.FORBIDDEN.equals(memoTemplateBO.getStatus())) {
            throw new BizException(BizErrorCodeEnum.OPERATION_FAILED, "当前需要复制的元数据无法操作，请稍后重试");
        }
        MemoTemplateBO insertMemoTemplateBO = StrategyConvert.buildMemoTemplateBO(memoTemplateBO, param);
        Boolean inserted = memoTemplateService.insertMemoTemplate(insertMemoTemplateBO);
        log.info("MemoTemplateAggService#copyMemoTemplateById 根据模板id拷贝模板完成 新增人Id：{}，结果:{}", param.get_user().getUserId(), inserted);
        return BizResponse.success(inserted);
    }
}
